<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属仓库" prop="warehouseId">
        <el-select v-model="queryParams.warehouseId" placeholder="请选择仓库" clearable @change="handleWarehouseChange">
          <el-option
            v-for="warehouse in warehousePullData"
            :key="warehouse.id"
            :label="warehouse.warehouseName"
            :value="warehouse.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="所属库区" prop="areaId">
        <el-select v-model="queryParams.areaId" placeholder="请选择库区" clearable>
          <el-option
            v-for="area in filteredAreaData"
            :key="area.id"
            :label="area.areaName"
            :value="area.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="盘点状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择盘点状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="盘点日期" prop="countDate">
        <el-date-picker clearable size="small"
          v-model="queryParams.countDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择盘点日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wms:count:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wms:count:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wms:count:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['wms:count:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="countList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center" >
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="盘点单ID" align="center" prop="id" />-->
      <el-table-column label="所属仓库" align="center"  prop="warehouseId"  >
        <template slot-scope="scope">
          <warehouse-tag  :options="warehousePullData" :value="scope.row.warehouseId"/>
        </template>

      </el-table-column>
      <el-table-column label="所属库区" align="center" prop="areaId"  >

        <template slot-scope="scope">
          <area-tag :options="areaPullData" :value="scope.row.areaId"/>
        </template>
      </el-table-column>
      <el-table-column label="盘点状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="盘点日期" align="center" prop="countDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.countDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wms:count:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wms:count:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改盘点单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属仓库" prop="warehouseId">
          <el-select
            v-model="form.warehouseId"
            placeholder="请选择仓库"
            clearable
            @change="handleWarehouseFormChange"
          >
            <el-option
              v-for="warehouse in warehousePullData"
              :key="warehouse.id"
              :label="warehouse.warehouseName"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="所属库区" prop="areaId">
          <el-select
            v-model="form.areaId"
            placeholder="请选择库区"
            clearable
            @change="handleAreaFormChange"
          >
            <el-option
              v-for="area in filteredFormAreaData"
              :key="area.id"
              :label="area.areaName"
              :value="area.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="盘点状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择盘点状态">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="盘点日期" prop="countDate">
          <el-date-picker clearable size="small"
            v-model="form.countDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择盘点日期">
          </el-date-picker>
        </el-form-item>
        <el-divider content-position="center">盘点明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddWmsInventoryCountDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteWmsInventoryCountDetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="wmsInventoryCountDetailList" :row-class-name="rowWmsInventoryCountDetailIndex" @selection-change="handleWmsInventoryCountDetailSelectionChange" ref="wmsInventoryCountDetail">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>

          <el-table-column label="货架" prop="rackId">
            <template slot-scope="scope">
              <el-select   @change="handleRackChange(scope.row)" v-model="scope.row.rackId" placeholder="请选择所属货架">
                <el-option
                  v-for="rack in filteredFormRackData"
                  :key="rack.id"
                  :label="rack.rackName"
                  :value="rack.id"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="物料" prop="itemId">
            <template slot-scope="scope">
              <el-select  v-model="scope.row.itemId" placeholder="请选择物料">
                <el-option
                  v-for="item in filteredItemData(scope.row.rackId)"
                  :key="item.id"
                  :label="item.itemName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </template>


          </el-table-column>

          <el-table-column label="盘点数量" prop="countedQuantity">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.countedQuantity"  :min="0" placeholder="请输入盘点数量"  :precision='2'/>
            </template>
          </el-table-column>
          <el-table-column label="实际库存数量" prop="actualQuantity">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.actualQuantity"  :min="0" placeholder="请输入实际库存数量"  :precision='2'/>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCount, getCount, delCount, addCount, updateCount, exportCount } from "@/api/wms/count";
import { pullWarehouse } from '@/api/wms/warehouse'
import { pullArea } from '@/api/wms/area'
import { pullRack } from '@/api/wms/rack'
import { pullItem } from '@/api/wms/item'
import { listInventory } from '@/api/inventory/inventory'
import { addReceiptOrder, updateReceiptOrder } from '@/api/wms/receiptOrder'

export default {
  name: "Count",
  data() {
    return {
      filteredFormAreaData:[],
      filteredFormRackData:[],
      warehousePullData: [],
      areaPullData: [],
      rackPullData: [],
      itemPullData:[],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedWmsInventoryCountDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 盘点单表格数据
      countList: [],
      // 盘点明细表格数据
      wmsInventoryCountDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 盘点单ID字典
      idOptions: [],
      // 所属仓库字典
      warehouseIdOptions: [],
      // 所属库区字典
      areaIdOptions: [],
      // 盘点状态字典
      statusOptions: [],
      // 盘点日期字典
      countDateOptions: [],
      // 创建人字典
      createByOptions: [],
      // 创建时间字典
      createTimeOptions: [],
      // 修改人字典
      updateByOptions: [],
      // 修改时间字典
      updateTimeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseId: null,
        areaId: null,
        status: null,
        countDate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        warehouseId:[
          { required: true, message: "仓库不能为空", trigger: "blur" }
        ],
        areaId:[
          { required: true, message: "库区不能为空", trigger: "blur" }
        ],
        status:[
          { required: true, message: "盘点状态不能为空", trigger: "blur" }
        ],
        countDate:[
          { required: true, message: "盘点日期不能为空", trigger: "blur" }
        ],
        // 针对明细中的各个字段进行验证
        wmsInventoryCountDetailList: [
          {
            type: 'array',
            required: true,
            message: '请添加至少一条盘点单详情信息',
            trigger: 'change'
          },
          {
            validator: this.validateDetailList,
            trigger: 'change'
          }]
      }
    };
  },
  created() {
    /** 查询仓库下拉数据 **/
    pullWarehouse().then(response => {
      this.warehousePullData = response.data;
    });

    /** 查询库区下拉数据 **/
    pullArea().then(response => {
      this.areaPullData = response.data;
    });

    /** 查询库区下拉数据 **/
    pullRack().then(response => {
      this.rackPullData = response.data;
    });
    /** 查询库区下拉数据 **/
    pullItem().then(response => {
      this.itemPullData = response.data;
    });
    this.getList();
    this.getDicts("${column.dictType}").then(response => {
      this.idOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.warehouseIdOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.areaIdOptions = response.data;
    });
    this.getDicts("count_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.countDateOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.createByOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.createTimeOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.updateByOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.updateTimeOptions = response.data;
    });
  },
  watch: {
    'form.warehouseId': function (newVal) {
      if (newVal) {
        console.log("选择的仓库ID:", newVal);
        // 根据选中的仓库ID加载库区选项
      }
      // 检查是否两个字段都有值
      this.checkBothSelected();
    },
    'form.areaId': function (newVal) {
      if (newVal) {
        console.log("选择的库区ID:", newVal);
      }
      // 检查是否两个字段都有值
      this.checkBothSelected();
    },
  },
  methods: {


    handleRackChange(row) {
      // 每次选择货架时重置物料选择
      row.itemId = null;
    },
    filteredItemData(rackId) {
      // 根据所选的货架 ID 过滤物料
      return this.itemPullData.filter(item => item.rackId === rackId);
    },

    handleAreaFormChange(){
      this.wmsInventoryCountDetailList=[]
    },
    handleWarehouseFormChange() {
      this.wmsInventoryCountDetailList=[]
      // 每次选择仓库时重置库区
      this.form.areaId = null;
      // 根据选中的仓库ID过滤库区数据
      this.filteredFormAreaData = this.areaPullData.filter(area => area.warehouseId === this.form.warehouseId);
    },
    handleWarehouseChange(warehouseId) {
      // 当仓库改变时，清空库区选择
      this.queryParams.areaId = null;

      // 根据选中的仓库ID过滤库区数据
      this.filteredAreaData = this.areaPullData.filter(area => area.warehouseId === warehouseId);

  },
    checkBothSelected() {
      if (this.form.warehouseId && this.form.areaId) {
        // 两个字段都有值时执行额外操作
        console.log("仓库和库区都已选择，执行额外操作");
        // 在此处添加额外操作的逻辑
        this.performExtraOperation();
      }
    },
    performExtraOperation() {
      // 这里是额外操作的逻辑
      // 例如，可以向服务器发送请求，或者更新其他数据
      console.log("执行额外操作的逻辑");
      const qp ={}
      qp.warehouseId=this.form.warehouseId
      qp.areaId=this.form.areaId

      this.filteredFormRackData = this.rackPullData.filter(rack => rack.areaId === this.form.areaId);




      if ( !this.form.id){
        listInventory(qp).then(response => {
          // this.wmsInventoryCountDetailList = response.rows;

          this.wmsInventoryCountDetailList = response.rows.map(item => ({
            ...item, // 保留原有的其他字段
            countedQuantity: item.quantity, // 将 quantity 映射为 countedQuantity

          }));

        });
      }


    },
    /** 查询盘点单列表 */
    getList() {
      this.loading = true;
      listCount(this.queryParams).then(response => {
        this.countList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 盘点单ID字典翻译
    idFormat(row, column) {
      return this.selectDictLabel(this.idOptions, row.id);
    },
    // 所属仓库字典翻译
    warehouseIdFormat(row, column) {
      return this.selectDictLabel(this.warehouseIdOptions, row.warehouseId);
    },
    // 所属库区字典翻译
    areaIdFormat(row, column) {
      return this.selectDictLabel(this.areaIdOptions, row.areaId);
    },
    // 盘点状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 盘点日期字典翻译
    countDateFormat(row, column) {
      return this.selectDictLabel(this.countDateOptions, row.countDate);
    },
    // 创建人字典翻译
    createByFormat(row, column) {
      return this.selectDictLabel(this.createByOptions, row.createBy);
    },
    // 创建时间字典翻译
    createTimeFormat(row, column) {
      return this.selectDictLabel(this.createTimeOptions, row.createTime);
    },
    // 修改人字典翻译
    updateByFormat(row, column) {
      return this.selectDictLabel(this.updateByOptions, row.updateBy);
    },
    // 修改时间字典翻译
    updateTimeFormat(row, column) {
      return this.selectDictLabel(this.updateTimeOptions, row.updateTime);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        warehouseId: null,
        areaId: null,
        status: null,
        countDate: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.wmsInventoryCountDetailList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加盘点单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCount(id).then(response => {
        this.form = response.data;
        this.wmsInventoryCountDetailList = response.data.wmsInventoryCountDetailList;

        this.open = true;
        this.title = "修改盘点单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.validateDetailList({}, this.wmsInventoryCountDetailList, (error) => {
        if (error) {
          // 如果有错误，提示用户
          this.$message.error(error.message);
        } else {
          this.$refs["form"].validate(valid => {
            if (valid) {
              this.form.wmsInventoryCountDetailList = this.wmsInventoryCountDetailList;
              if (this.form.id != null) {
                updateCount(this.form).then(response => {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                });
              } else {
                addCount(this.form).then(response => {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                });
              }
            }
          });
        }
      });



    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除盘点单编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCount(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
	/** 盘点明细序号 */
    rowWmsInventoryCountDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 盘点明细添加按钮操作 */
    handleAddWmsInventoryCountDetail() {
      let obj = {};
      obj.itemId = "";
      obj.rackId = "";
      obj.countedQuantity = "";
      obj.actualQuantity = "";
      obj.remark = "";
      this.wmsInventoryCountDetailList.push(obj);
    },
    /** 盘点明细删除按钮操作 */
    handleDeleteWmsInventoryCountDetail() {
      if (this.checkedWmsInventoryCountDetail.length == 0) {
        this.$alert("请先选择要删除的盘点明细数据", "提示", { confirmButtonText: "确定", });
      } else {
        this.wmsInventoryCountDetailList.splice(this.checkedWmsInventoryCountDetail[0].index - 1, 1);
      }
    },
    /** 单选框选中数据 */
    handleWmsInventoryCountDetailSelectionChange(selection) {
      if (selection.length > 1) {
        this.$refs.wmsInventoryCountDetail.clearSelection();
        this.$refs.wmsInventoryCountDetail.toggleRowSelection(selection.pop());
      } else {
        this.checkedWmsInventoryCountDetail = selection;
      }
    },
    validateDetailList(rule, value, callback) {
      if (!value || value.length === 0) {
        return callback(new Error('请至少添加一条明细'));
      }

      // 遍历明细列表，逐一检查每个字段
      for (let i = 0; i < value.length; i++) {
        let detail = value[i];
        if (!detail.itemId) {
          return callback(new Error('第 ' + (i + 1) + ' 行的物料不能为空'));
        }
        if (!detail.countedQuantity) {
          return callback(new Error('第 ' + (i + 1) + ' 行的盘点数量不能为空'));
        }
        if (!detail.actualQuantity) {
          return callback(new Error('第 ' + (i + 1) + ' 行的实际库存数量不能为空'));
        }
        if (!detail.rackId) {
          return callback(new Error('第 ' + (i + 1) + ' 行的所属货架不能为空'));
        }

      }
      // 验证通过
      callback();
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有盘点单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportCount(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
